import React, { Component } from 'react';
import { Relax } from 'iflux2';
import { Row, Col, Button, Input, Upload, Modal, Icon, Form } from 'antd';
import { Map, List } from 'immutable';

import moment from 'moment';
import Image from 'components/Image'
import QmIcon from 'components/QmIcon';
import Stars from './stars';

import noop from 'util/noop';

const FormItem = Form.Item;

moment.locale('zh-cn')

@Relax
export default class CommentDetail extends Component {
  static defaultProps = {
    comment: Map(),
    commentSuns: List(),
    commentReplies: List(),
    addCommentReply: noop,
    updateCommentShowState: noop,
    updateReplyShowState: noop,
    deleteComments: noop
  };

  constructor(props) {
    super(props);

    this.state = {
      previewVisible: false,
      previewImage: '',
      fileList: []
    }
  }

  componentDidMount() {
    this.setState({ fileList: this.convert(this.props.commentSuns) });
  }

  componentWillReceiveProps(nextProps) {
    this.setState({ fileList: this.convert(nextProps.commentSuns) });
  }

  render() {
    const { comment, commentSuns } = this.props;

    return (
      <div className="evaluate-detail">
        <div className="avatar">

        </div>
        <div>
          <div className="t-primary lh24">
            <span>{comment.get('optName')}</span>
            <Stars starLevel={comment.get('score')} className="pull-right" />
          </div>
          <p className="t-grayer pushb">评论：{comment.get('goodsName')} <span className="pushl">{moment(comment.get('optTime')).fromNow()}</span></p>
          <p className="font-14 pushb">{comment.get('content')}</p>
          {commentSuns.isEmpty() ? null :
            <div className="pushb">
              <Upload
                action="/upload.do"
                listType="picture-card"
                fileList={this.state.fileList}
                onPreview={this.handlePreview}
                className="upload-qm un-deletable"
              />
              <Modal visible={this.state.previewVisible} footer={null} onCancel={this.handleCancel1}>
                <Image alt="example" style={{ width: '100%' }} src={this.state.previewImage} auto={true} />
              </Modal>
            </div>
          }
          {
            comment.get('showState') === 1 ?
              <div className="pushb">
                <Button type={"ghost"} onClick={e => this.updateCommentShowState(0, e)}>
                  前台隐藏
                  </Button>
              </div> :
              <div className="pushb">
                <Button type={"primary"} onClick={e => this.updateCommentShowState(1, e)}>
                  前台显示
                  </Button>
              </div>
          }
          {this.renderReply()}
          <div className="pushb">
            <ReplyForm comment={comment} addCommentReply={this.props.addCommentReply} />
          </div>
        </div>
      </div>
    )
  }

  renderReply() {
    const { commentReplies } = this.props;
    if (commentReplies.isEmpty()) {
      return null;
    }

    let replyContentList = commentReplies.map(reply =>
      <p className="pushb">
        <span className="show-ct t-grayer" onClick={e => this.updateReplyShowState(reply, e)}>
          <QmIcon type={reply.get('showState') === 1 ? 'eye' : 'eye-close'} />
        </span>
        <span className="t-primary pushr">{reply.get('optName')}回复{reply.get('replyName')}：</span>
        {reply.get('content')}
      </p>
    );

    return (
      <div className="comments-dialogue pushb">
        <div className="right-top">
        </div>
        {replyContentList}
      </div>
    );
  }

  /**
   * 预览图片
   */
  handleCancel1 = () => {
    this.setState({
      previewVisible: false
    })
  }

  handlePreview = (file) => {
    this.setState({
      previewImage: file.url || file.thumbUrl,
      previewVisible: true,
    });
  }

  /**
   * 回复内容的onChange
   */
  handleContent = (e) => {
    this.setState({ replyCotent: e.target.value });
  }

  /**
   * 将晒单记录转为图片列表, 展示用
   * @param {*} commentSuns 
   */
  convert(commentSuns = List()) {
    return commentSuns.map((commentSun, index) => {
      let img = commentSun.get('pictureUrl');
      if(/^https?:\/\//.test(img)){
            img = img.replace(/https?:\/\//,"//");
        }else{
            img = $CONST_HOST['v_oss_domain_img'] + img;
        }
      return {
        'uid': index,
        'name': commentSun.get('pictureUrl'),
        'status': 'done',
        'url': img
      }
    })
  }



  /**
   * 切换评价的显示状态. 如果当前状态为显示, 则改为隐藏. 如果当前状态为隐藏, 则改为显示
   */
  updateCommentShowState = (showState, e) => {
    e.preventDefault()
    let { comment } = this.props;
    this.props.updateCommentShowState({
      'oid': comment.get('billId'),
      'commentId': comment.get('id'),
      'showState': showState
    })
  }

  /**
   * 切换回复的显示状态. 如果当前状态为显示, 则改为隐藏. 如果当前状态为隐藏, 则改为显示
   */
  updateReplyShowState = (reply) => {
    this.props.updateReplyShowState({
      'commentId': reply.get('commentId'),
      'id': reply.get('id'),
      'showState': reply.get('showState') === 1 ? 0 : 1
    })
  }

}

class ReplyForm extends Component {

  render() {
    const { getFieldDecorator } = this.props.form;
    const contentField = getFieldDecorator('replyContent', {
      rules: [
        {
          required: true, message: '请输入回复内容'
        },
        {
          min: 1, max: 100, type: 'string', message: '回复内容需在100字以内'
        }
      ]
    })(
      <Input style={{ width: '405px' }} maxLength={100} placeholder='请输入回复内容' />
      );
    return (
      <Form layout="inline">
        <FormItem>
          {contentField}
          <Button type="primary" className="w80 pull-right" onClick={this.addCommentReply}>回复</Button>
        </FormItem>
      </Form>
    )
  }

  /**
   * 添加评价回复
   */
  addCommentReply = (e) => {
    e.preventDefault();

    const { form, comment } = this.props;
    const { setFieldsValue } = form;
    let self = this;
    form.validateFields(['replyContent'], (err, values) => {
      if (err) {
        return;
      }
      let { comment } = self.props;
      let commentReply = {
        'commentId': comment.get('id'),
        'replyId': comment.get('optId'),
        'replyName': comment.get('optName'),
        'content': values['replyContent']
      }
      self.props.addCommentReply(commentReply).then(result => {
        setFieldsValue({ 'replyContent': '' })
      });
    })
  }
}

ReplyForm = Form.create()(ReplyForm);